package com.stu.service.impl;

import com.stu.mapper.UserMapper;
import com.stu.pojo.User;
import com.stu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务实现类
 * @author zy
 * @date 2025/4/12
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User createUser(User user) {
        // 检查用户名是否已存在
        if (userMapper.selectByUserName(user.getUserName()) != null) {
            return null;
        }

        // 设置默认值
        LocalDateTime now = LocalDateTime.now();
        user.setUserCreated(now);
        user.setUserUpdated(now);
        user.setStatus(1); // 默认启用状态
        user.setVersion(1); // 初始版本

        // 插入数据库
        if (userMapper.insert(user) > 0) {
            return user; // 返回包含生成ID的用户对象
        }
        return null;
    }

    @Override
    public boolean updateUser(User user) {
        User existingUser = userMapper.selectById(user.getUserId());
        if (existingUser == null) {
            return false;
        }

        // 保留创建时间不变
        user.setUserCreated(existingUser.getUserCreated());
        // 设置更新时间
        user.setUserUpdated(LocalDateTime.now());

        return userMapper.update(user) > 0;
    }

    @Override
    public boolean deleteUser(Integer userId) {
        return userMapper.deleteById(userId) > 0;
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User getUserByUserName(String userName) {
        return userMapper.selectByUserName(userName);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public boolean changeUserStatus(Integer userId, Integer status) {
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updateStatus(userId, status, now) > 0;
    }

    @Override
    public User login(String account, String password) {
        // 尝试用用户名查找
        User user = userMapper.selectByUserName(account);

        // 如果没找到且account包含@，尝试用邮箱查找
        if (user == null && account.contains("@")) {
            user = userMapper.selectByEmail(account);
        }

        // 验证用户是否存在、密码是否正确、账号是否启用
        if (user != null &&
                password.equals(user.getUserPassword()) &&
                user.getStatus() == 1) {
            return user;
        }

        return null;
    }
}
